<template>
    <div ref="scrollContainer" class="scroll-container" @wheel.prevent="handleScroll">
        <div ref="scrollWrapper" class="scroll-wrapper" :style="{ left: left + 'px' }">
            <slot />
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue';

const padding = ref(15); // tag's padding  
const left = ref(0);

// 获取元素的引用  
const scrollContainer = ref(null);
const scrollWrapper = ref(null);

function handleScroll(e) {
    const eventDelta = e.wheelDelta || -e.deltaY * 3; // wheelDelta:-120; deltaY:-120  
    const container = scrollContainer.value; // 外面的 container  
    const containerWidth = container.offsetWidth; // 外面的 container 的宽度  
    const wrapper = scrollWrapper.value; // 里面的 wrapper  
    const wrapperWidth = wrapper.offsetWidth; // 里面的宽度  

    if (eventDelta > 0) {
        left.value = Math.min(0, left.value + eventDelta); // min() 方法可返回指定的数字中带有最低值的数字。  
    } else {
        if (containerWidth - padding.value < wrapperWidth) {
            if (left.value < - (wrapperWidth - containerWidth + padding.value)) {
                left.value = 1;
            } else {
                left.value = Math.max(left.value + eventDelta, containerWidth - wrapperWidth - padding.value);
            }
        } else {
            left.value = 0;
        }
    }
}

function moveToTarget(target) {
    const container = scrollContainer.value;
    const containerWidth = container.offsetWidth;
    const targetLeft = target.offsetLeft;
    const targetWidth = target.offsetWidth;

    if (targetLeft < -left.value) {
        // tag in the left  
        left.value = -targetLeft + padding.value;
    } else if (targetLeft + padding.value > -left.value && targetLeft + targetWidth < -left.value + containerWidth - padding.value) {
        // tag in the current view  
        // eslint-disable-line  
    } else {
        // tag in the right  
        left.value = - (targetLeft - (containerWidth - targetWidth) + padding.value);
    }
}
</script>

<style scoped lang="scss">
.scroll-container {
    white-space: nowrap;
    position: relative;
    overflow: hidden;
    width: 100%;

    .scroll-wrapper {
        position: absolute;
    }
}
</style>